class Solution
{
public:
    vector<int> spiralArray(vector<vector<int>>& array)
    {
        if (array.empty())
            return {};
        int l = 0, r = array[0].size() - 1, t = 0, b = array.size() - 1;
        vector<int> res;

        while (true)
        {
            for (int i = l; i <= r; i++) res.push_back(array[t][i]);
            if (++t > b) break;
            for (int i = t; i <= b; i++) res.push_back(array[i][r]);
            if (l > --r) break;
            for (int i = r; i >= l; i--) res.push_back(array[b][i]);
            if (t > --b) break;
            for (int i = b; i >= t; i--) res.push_back(array[i][l]);
            if (++l > r) break;
        }

        return res;
    }
};